import React from 'react';
import { connect } from 'react-redux';
import { Form, Tabs, Badge, Col, Row, Input, Popover } from 'antd';
import menuRoute from 'routes/menuRoute';
import config from 'config';
import SearchArea from 'components/search-area';
import moment from 'moment';
import { messages } from 'share/common';
import CustomTable from 'containers/setting/contract-type-define/custom-table';

const TabPane = Tabs.TabPane;
const Search = Input.Search;

class Contract extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tabValue: 'unapproved',
      loading1: false,
      loading2: false,
      contractStatus: {
        6002: { label: messages('my.contract.state.cancel'/*已取消*/), state: 'default' },
        6003: { label: messages('my.contract.state.finish'/*已完成*/), state: 'success' },
        1001: { label: messages('my.contract.state.generate'/*编辑中*/), state: 'processing' },
        6001: { label: messages('my.contract.state.hold'/*暂挂*/), state: 'warning' },
        1002: { label: messages('my.contract.state.submitted'/*审批中*/), state: 'processing' },
        1005: { label: messages('my.contract.state.rejected'/*已驳回*/), state: 'error' },
        1004: { label: messages('my.contract.state.confirm'/*已通过*/), state: 'success' },
        1003: { label: messages('my.contract.state.withdrawal'/*已撤回*/), state: 'warning' },
      },
      SearchForm1: [
        {
          type: 'input',
          id: 'contractName',
          label: messages('my.contract.name'/*合同名称*/)
        },
        {
          type: 'select',
          id: 'contractTypeId',
          label: messages('my.contract.type'),/*合同类型*/
          getUrl: `${config.contractUrl}/api/contract/type/contract/type/by/company`,
          method: 'get',
          options: [],
          searchKey: 'contractTypeName',
          getParams: { companyId: this.props.company.id },
          labelKey: 'contractTypeName',
          valueKey: 'id',
          placeholder: messages('common.please.enter'/*请输入*/)
        },
        {
          type: 'list',
          listType: 'bgtUser',
          options: [],
          id: 'createdBy',
          label: messages('common.applicant'),
          labelKey: 'fullName',
          valueKey: 'id',
          single: true,
          listExtraParams: { setOfBooksId: this.props.company.setOfBooksId }
        },
        {
          type: 'items', id: 'dateRange', items: [
            {
              type: 'date',
              id: 'submittedDateFrom',
              label: messages('contract.search.date.from'/*提交时间从*/)
            },
            {
              type: 'date',
              id: 'submittedDateTo',
              label: messages('contract.search.date.to'/*提交时间至*/)
            }
          ]
        },
        {
          type: 'select',
          id: 'currency',
          label: messages('common.currency'/*币种*/),
          options: [],
          getUrl: `/api/currency/status/query/by/setOfBooksId?userOId=${props.user.userOID}`,
          method: 'get',
          labelKey: 'currency',
          valueKey: 'currency',
        },
        {
          type: 'items', id: 'amountRange', items: [
            {
              type: 'input',
              id: 'amountFrom',
              label: messages('my.contract.amount.from'/*合同金额从*/)
            },
            { type: 'input', id: 'amountTo', label: messages('my.contract.amount.to'/*合同金额至*/) }
          ]
        },
        {
          type: 'input', id: 'remark', label: messages('common.comment'/*备注*/)
        }
      ],
      columns: [
        {
          title: messages('my.contract.number'/*合同编号*/),
          dataIndex: 'contractNumber',
          width: 200,
          align: 'center',
          render: desc => <span><Popover content={desc}>{desc ? desc : ''}</Popover></span>
        },
        {
          title: messages('my.contract.name'/*合同名称*/), dataIndex: 'contractName', align: 'center',
          render: desc => <span><Popover content={desc}>{desc ? desc : ''}</Popover></span>
        },
        {
          title: messages('my.contract.type'/*合同类型*/),
          dataIndex: 'contractTypeName',
          align: 'center',
          render: desc => <span><Popover content={desc}>{desc ? desc : ''}</Popover></span>
        },
        {
          title: messages('contract.createdBy'/*申请人*/), dataIndex: 'created', align: 'center',
          render: value => value && value.fullName + ' - ' + value.employeeId
        },
        {
          title: messages('common.submit.date'/*提交时间*/),
          dataIndex: 'submittedDate',
          align: 'center',
          render: value => value ? moment(value)
            .format('YYYY-MM-DD') : '-'
        },
        {
          title: messages('my.contract.currency'/*币种*/),
          dataIndex: 'currency',
          align: 'center',
          width: '5%'
        },
        {
          title: messages('my.contract.amount'/*金额*/), dataIndex: 'amount', align: 'center',
          render: desc => this.filterMoney(desc)
        },
        {
          title: messages('common.comment'), key: 'remark', dataIndex: 'remark', align: 'center',
          render: desc => <span><Popover content={desc}>{desc ? desc : '-'}</Popover></span>
        },
        {
          title: messages('common.column.status'/*状态*/),
          dataIndex: 'status',
          align: 'center',
          width: 100,
          render: (value) => <Badge status={this.state.contractStatus[value].state}
                                    text={this.state.contractStatus[value].label}/>
        },
      ],
      SearchForm2: [
        {
          type: 'input',
          id: 'contractName',
          label: messages('my.contract.name'/*合同编号*/)
        },
        {
          type: 'input',
          id: 'keyword',
          label: messages('contract.search.name.employeeId'/*申请人姓名/工号*/)
        },
        {
          type: 'select',
          id: 'contractTypeId',
          label: messages('my.contract.type'),
          getUrl: `${config.contractUrl}/api/contract/type/query/all`,
          options: [],
          method: 'get',
          valueKey: 'id',
          labelKey: 'contractTypeName',
          getParams: { setOfBooksId: this.props.company.setOfBooksId }
        },
        {
          type: 'items', id: 'dateRange', items: [
            {
              type: 'date',
              id: 'submittedDateFrom',
              label: messages('contract.search.date.from'/*提交时间从*/)
            },
            {
              type: 'date',
              id: 'submittedDateTo',
              label: messages('contract.search.date.to'/*提交时间至*/)
            }
          ]
        },
      ],
      url: `${config.contractUrl}/api/contract/header/confirm/query`,
      unApproveSearchParams: {},
      approveSearchParams: {},
      columns2: [
        {
          title: messages('my.contract.number'/*合同编号*/),
          dataIndex: 'contractNumber',
          width: 200,
          render: desc => <Popover placement="topLeft" content={desc}>{desc ? desc : ''}</Popover>
        },
        {
          title: messages('my.contract.name'/*合同名称*/),
          dataIndex: 'contractName',
          render: desc => <Popover placement="topLeft" content={desc}>{desc ? desc : ''}</Popover>
        },
        {
          title: messages('my.contract.type'/*合同类型*/),
          dataIndex: 'contractTypeName',
          render: desc => <Popover placement="topLeft" content={desc}>{desc ? desc : ''}</Popover>
        },
        {
          title: messages('my.contract.signDate'/*签署日期*/),
          dataIndex: 'signDate',
          width: 100,
          render: desc => <span><Popover placement="topLeft" content={moment(desc)
            .format('YYYY-MM-DD')}>{desc ? moment(desc)
            .format('YYYY-MM-DD') : '-'}</Popover></span>,
        },
        {
          title: messages('my.contract.part'),
          dataIndex: 'partnerCategoryName',
          render: (value, record) => {
            return (
              value ? <div>{value}<span className="ant-divider"/>{record.partnerName}</div> : '-'
            );
          }
        },
        {
          title: messages('my.contract.currency'/*币种*/),
          dataIndex: 'currency',
          width: '5%'
        },
        {
          title: messages('my.contract.amount'/*合同金额*/),
          dataIndex: 'amount',
          render: desc => this.filterMoney(desc)
        },
        {
          title: messages('common.comment'),
          key: 'remark',
          dataIndex: 'remark',
          render: desc => <Popover placement="topLeft" content={desc}>{desc ? desc : '-'}</Popover>
        },
        {
          title: messages('common.column.status'/*状态*/),
          dataIndex: 'status',
          width: 100,
          render: (value) => <Badge status={this.state.contractStatus[value].state} text={this.state.contractStatus[value].label}/>
        },
      ],
      unapprovedData: [],
      approvedData: [],
      unapprovedPagination: {
        total: 0
      },
      approvedPagination: {
        total: 0
      },
      unapprovedPage: 0,
      unapprovedPageSize: 10,
      approvedPage: 0,
      approvedPageSize: 10,
      contractDetail: menuRoute.getRouteItem('approve-contract-detail', 'key'), //合同详情
    };
  }

  //未审批搜索
  unapprovedSearch = (values) => {
    values.submittedDateFrom && (values.submittedDateFrom = moment(values.submittedDateFrom)
      .format('YYYY-MM-DD'));
    values.submittedDateTo && (values.submittedDateTo = moment(values.submittedDateTo)
      .format('YYYY-MM-DD'));
    this.setState({ unApproveSearchParams: values, approveSearchParams: values }, () => {
      this.customTable.search(this.state.unApproveSearchParams);
    });
  };

  //审批搜索
  approvedSearch = (values) => {
    values.submittedDateFrom && (values.submittedDateFrom = moment(values.submittedDateFrom)
      .format('YYYY-MM-DD'));
    values.submittedDateTo && (values.submittedDateTo = moment(values.submittedDateTo)
      .format('YYYY-MM-DD'));
    this.setState({ approveSearchParams: values, unApproveSearchParams: values }, () => {
      this.customTable2.search(this.state.approveSearchParams);
    });
  };

  //进入合同详情页
  handleRowClick = (record) => {
    this.context.router.push(this.state.contractDetail.url.replace(':id', record.id)
      .replace(':status', this.state.tabValue));
  };


  handleTabsChange = (key) => {
    this.setState({
      tabValue: key
    });
  };

  renderContent() {
    const { tabValue, searchParams, SearchForm1, columns, columns2 } = this.state;
    if (tabValue === 'unapproved') {
      return (<div>
        <SearchArea searchForm={SearchForm1}
                    maxLength={4}
                    clearHandle={() => { }}
                    submitHandle={this.unapprovedSearch}/>
        <div className='divider'/>
        <Row gutter={24} style={{ marginBottom: 12 }}>
          <Col span={18}/>
          <Col span={6}>
            <Search
              placeholder={messages('my.please.input.number')}
              onSearch={e => {
                this.customTable && this.customTable.search({
                  ...searchParams,
                  contractNumber: e
                });
              }}
              className="search-number"
              enterButton
            />
          </Col>
        </Row>
        <CustomTable
          ref={ref => this.customTable = ref}
          columns={columns}
          onClick={this.handleRowClick}
          url={`${config.contractUrl}/api/contract/header/confirm/query`}
        />
      </div>);
    } else {
      return (<div>
        <SearchArea searchForm={SearchForm1}
                    clearHandle={() => { }}
                    maxLength={4}
                    submitHandle={this.approvedSearch}/>

        <Row gutter={24} style={{ marginBottom: 12 }}>
          <Col span={18}/>
          <Col span={6}>
            <Search
              placeholder={messages('my.please.input.number')}
              onSearch={e => this.customTable2 && this.customTable2.search({
                ...searchParams,
                contractNumber: e
              })}
              className="search-number"
              enterButton
            />
          </Col>
        </Row>
        <CustomTable
          ref={ref => this.customTable2 = ref}
          columns={columns2}
          onClick={this.handleRowClick}
          url={`${config.contractUrl}/api/contract/header/confirmEd/query`}
        />
      </div>);
    }
  }

  render() {
    const { tabValue } = this.state;
    return (
      <div className="approve-contract">
        <Tabs defaultActiveKey={tabValue} onChange={this.handleTabsChange}>
          <TabPane tab={messages('contract.unchecked'/*未复核*/)} key="unapproved">
          </TabPane>
          <TabPane tab={messages('contract.checked'/*已复核*/)} key="approved">
          </TabPane>
        </Tabs>
        {this.renderContent()}
      </div>
    );
  }
}

Contract.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company
  };
}

const wrappedContract = Form.create()((Contract));

export default connect(mapStateToProps, null, null, { withRef: true })(wrappedContract);
